#coding: utf-8
from __future__ import with_statement
import os
#import posixpath
#import pprint
from re import match
#from functools import wraps
from fabric.api import *
#from fabric.contrib import files
#from fabric import state
#from fabric import network
#from fabric import operations

OS_DETECTION_ERROR_MESSAGE = '''
os not detected or not in list of know os's
'''

def platform_info():
    output = run('python -c "import platform; print platform.dist()"')
    print('bits equals %s' % output)

def exists(path, prefix=run, verbose=False):
    """
    Return True if given path exists on targeted host.
    """
    func = prefix and local or sudo or run
    cmd = 'test -e "%s"' % path
    if verbose:
        with settings(warn_only=True):
            return not func(cmd).failed
    # Otherwise, be quiet
    with settings(hide('everything'), warn_only=True):
        return not func(cmd).failed

def _codename(distname, version, id):
    patterns = [
        ('lenny', ('debian', '^5', '')),
        ('squeeze', ('debian', '^6', '')),
        ('lucid', ('Ubuntu', '^10.04', '')),
        ('maverick', ('Ubuntu', '^10.10', '')),
    ]
    for name, p in patterns:
        if match(p[0], distname) and match(p[1], version) and match(p[2], id):
            return name

def info():
    if 'conf' in env and 'OS' in env.conf:
        return env.conf['OS']
    output = run('python -c "import platform; print platform.dist()"')
    name = _codename(*eval(output))
    if name is None:
        abort(OS_DETECTION_ERROR_MESSAGE)

    puts('%s detected' % name)
    return name
